import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('./picture/flower_rgb.png', 1)
# R-G-B三种染色直方图
countb = np.zeros(256, np.float32)
countg = np.zeros(256, np.float32)
countr = np.zeros(256, np.float32)

for i in range(img.shape[0]):
    for j in range(img.shape[1]):
        (b,g,r) = img[i,j]
        b = int(b)
        g = int(g)
        r = int(r)
        countb[b] += 1 # 统计该像素出现的次数
        countg[g] += 1
        countr[r] += 1
countb = countb / (img.shape[0] * img.shape[1]) # 得到概率
countg = countg / (img.shape[0] * img.shape[1])
countr = countr / (img.shape[0] * img.shape[1])
x = np.linspace(0,255,256)
plt.figure()
plt.bar(x, countb,color = 'b')
plt.figure()
plt.bar(x, countg,color = 'g')
plt.figure()
plt.bar(x, countr,color = 'r')
plt.show()


# 计算直方图累计概率
for i in range(1,256):
    countb[i] += countb[i - 1]
    countg[i] += countg[i - 1]
    countr[i] += countr[i - 1]
#映射表
mapb = countb * 255
mapg = countg * 255
mapr = countr * 255

dat = np.zeros(img.shape, np.uint8)
for i in range(img.shape[0]):
    for j in range(img.shape[1]):
        (b,g,r) = img[i, j]
        dat[i, j] = (mapb[b],mapg[g],mapr[r])
cv2.imshow('dat', dat)
cv2.waitKey(0)

